package com.example.servlet;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author Huangyt
 * @version 1.0
 * @date 2020/9/19 21:04
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    private static final String PASSWORD = "123456";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HashMap<String, Object> resMap = new HashMap<>();
        //1、接收页面传递的参数，用户名&密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2、判定用户名&密码是否正确

        //3、如果正确，响应登录成功的信息
        if(PASSWORD.equals(password)){
            resMap.put("success", true);
            resMap.put("message", "登录成功");
            request.getSession().setAttribute("username", username); //保存用户登录信息
        }
        //4、如果不正确，响应登录失败的信息
        else {
            resMap.put("success", false);
            resMap.put("message", "登录失败");
        }
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(resMap)); //response返回json数据
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
